﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using KindleComic.Core;
using System.Xml.Linq;
using System.Threading;

namespace KindleComic
{
    public partial class FrmComicDownload : Form
    {
        public FrmComicDownload()
        {
            InitializeComponent();
        }

        private void ComicDownload_Load(object sender, EventArgs e)
        {
            this.tabControl.SelectedIndex = 0;
            LoadComicSource();
            LoadNavigator();

            initDownloadList();

        }

        private Dictionary<string, ComicSource> ComicSourceDic = new Dictionary<string, ComicSource>();

        private int PageCount = 1;

        private int PageNum = 1;

        private void LoadComicSource()
        {
            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(x => x.GetTypes())
                .Where(x => x.BaseType == typeof(ComicSource))
                .ToList();
            this.cboComicSource.Items.Add("全部");
            foreach (var type in types)
            {
                var comicSource = (ComicSource)Activator.CreateInstance(type);
                ComicSourceDic.Add(comicSource.ComicSourceName, comicSource);
                this.cboComicSource.Items.Add(comicSource.ComicSourceName);
            }
            this.cboComicSource.SelectedIndex = 0;
        }

        private void initDownloadList()
        {
            var list = XMLOpteration.Query()
                 .Elements("comicInfo")
                 .Elements("chapterList")
                 .Elements("chapter")
                 .Select(x => new DownloadInfo
                 {
                     ComicName = x.Parent.Parent.Element("name").Value,
                     ComicAuthor = x.Parent.Parent.Element("author").Value,
                     ComicUrl = x.Parent.Parent.Element("url").Value,
                     ChapterName = x.Element("name").Value,
                     PageCount = x.Element("imgList").Elements("img").Count(),
                     DownloadedPageCount = x.Element("imgList").Elements("img").Where(p => p.Attribute("downloaded").Value == "true").Count()
                 }).ToList();

            this.dgvDownloadList.DataSource = list;
            this.dgvDownloadList.Columns["ChapterName"].HeaderText = "章节";
            this.dgvDownloadList.Columns["ChapterName"].DisplayIndex = 0;
            this.dgvDownloadList.Columns["ComicName"].HeaderText = "漫画";
            this.dgvDownloadList.Columns["ComicName"].DisplayIndex = 1;
            this.dgvDownloadList.Columns["PageCount"].HeaderText = "总页数";
            this.dgvDownloadList.Columns["PageCount"].HeaderText = "总页数";
            this.dgvDownloadList.Columns["PageCount"].DisplayIndex = 2;
            this.dgvDownloadList.Columns["DownloadedPageCount"].HeaderText = "已下载页数";
            this.dgvDownloadList.Columns["DownloadedPageCount"].DisplayIndex = 3;
            this.dgvDownloadList.Columns["ComicAuthor"].HeaderText = "作者";
            this.dgvDownloadList.Columns["ComicAuthor"].DisplayIndex = 4;
            this.dgvDownloadList.Columns["ComicUrl"].HeaderText = "网址";
            this.dgvDownloadList.Columns["ComicUrl"].DisplayIndex = 5;
        }

        private void Search()
        {
            var currentSource = this.cboComicSource.Text;
            var searchKey = this.txtKey.Text;
            PageCount = 1;
            if (currentSource == "全部")
            {
                var i = 0;
                foreach (var keyValuePair in ComicSourceDic)
                {
                    ComicSource source = keyValuePair.Value;
                    ShowSearchList(source, searchKey, PageNum,i>0);
                    i++;
                }
            }
            else
            {
                ComicSource source = ComicSourceDic[currentSource];
                ShowSearchList(source, searchKey, PageNum);
            }
            ////为空时使用所有源
            //if (currentSource == "")
            //{
            //    //使用所有源时，分页分为程序显示的分页和实际源的分页
            //    int realPage = (int)Math.Ceiling(PageNum * 1.0 / ComicSourceDic.Count);
            //    int sourceIndex = PageNum % ComicSourceDic.Count;

            //    ComicSource source = ComicSourceDic.ElementAt(sourceIndex).Value;
            //    ShowSearchList(source, searchKey, realPage);
            //}
            //else
            //{
            //}
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            PageNum = 1;
            Search();
        }

        private void LoadNavigator()
        {
            if (PageCount == 0 || PageCount == 1)
            {
                bindingNavigator1.MoveFirstItem.Enabled = false;
                bindingNavigator1.MoveLastItem.Enabled = false;
                bindingNavigator1.MoveNextItem.Enabled = false;
                bindingNavigator1.MovePreviousItem.Enabled = false;
                bindingNavigator1.PositionItem.Text = "1";
                bindingNavigator1.CountItem.Text = "共1页";
            }
            else
            {
                bindingNavigator1.MoveFirstItem.Enabled = false;
                bindingNavigator1.MoveLastItem.Enabled = true;
                bindingNavigator1.MoveNextItem.Enabled = true;
                bindingNavigator1.MovePreviousItem.Enabled = false;
                bindingNavigator1.PositionItem.Text = PageNum.ToString();
                bindingNavigator1.CountItem.Text = "共" + PageCount.ToString() + "页";
            }
        }

        private void ShowSearchList(ComicSource source, string searchKey, int page,bool append=false)
        {
            List<ComicInfo> comicList = new List<ComicInfo>();
            var searchListInfo = source.GetSearchListAsync(searchKey, page).Result;
            comicList = searchListInfo.Item1;
            if (searchListInfo.Item2 > PageCount)
                PageCount = searchListInfo.Item2;

            LoadNavigator();
            int i = 0;
            if (!append)
            {
                this.flpanelContent.Controls.Clear();
            }
            foreach (var item in comicList)
            {
                i++;
                var comic = new ucComic();
                comic.ComicName = item.ComicName;
                comic.ComicUrl = item.ComicUrl;
                comic.ComicCover = item.CoverUrl;
                comic.ComicAuthor = item.ComicAuthor;
                comic.ComicSource = source.ComicSourceName;
                comic.Margin = new Padding(10, 0, 0, 10);
                comic.Tag = source;
                comic.ucDoubleClick += ShowComicDetails;
                this.flpanelContent.Controls.Add(comic);
            }
        }

        private void BindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            int currentPage = Convert.ToInt32(bindingNavigator1.PositionItem.Text);
            if (currentPage < PageCount)
            {
                PageNum = currentPage + 1;
                bindingNavigator1.PositionItem.Text = PageNum.ToString();
                Search();
                //LoadData(page, dgvDemo);
                if (PageNum == PageCount)
                {
                    bindingNavigator1.MoveNextItem.Enabled = false;
                    bindingNavigator1.MoveLastItem.Enabled = false;
                }
                if (PageNum >= 2)
                {
                    bindingNavigator1.MovePreviousItem.Enabled = true;
                    bindingNavigator1.MoveFirstItem.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("当前是最后一页", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void BindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
        {
            int currentPage = Convert.ToInt32(bindingNavigator1.PositionItem.Text);
            if (currentPage >= 2)
            {
                PageNum = currentPage - 1;
                bindingNavigator1.PositionItem.Text = PageNum.ToString();
                Search();
                //LoadData(page, dgvDemo);
                if (PageNum == 1)
                {
                    bindingNavigator1.MovePreviousItem.Enabled = false;
                    bindingNavigator1.MoveFirstItem.Enabled = false;
                }
                if (PageNum <= PageCount)
                {
                    bindingNavigator1.MoveNextItem.Enabled = true;
                    bindingNavigator1.MoveLastItem.Enabled = true;
                }

            }
            else
            {
                MessageBox.Show("当前是第1页", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void BindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
        {
            PageNum = PageCount;
            Search();
            //LoadData(pageCount, dgvDemo);
            bindingNavigator1.PositionItem.Text = PageCount.ToString();
            bindingNavigator1.MoveLastItem.Enabled = false;
            bindingNavigator1.MoveNextItem.Enabled = false;
            bindingNavigator1.MovePreviousItem.Enabled = true;
            bindingNavigator1.MoveFirstItem.Enabled = true;
        }

        private void BindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
        {
            PageNum = 1;
            Search();
            //LoadData(1, dgvDemo);
            bindingNavigator1.PositionItem.Text = "1";
            bindingNavigator1.MoveFirstItem.Enabled = false;
            bindingNavigator1.MovePreviousItem.Enabled = false;
            bindingNavigator1.MoveNextItem.Enabled = true;
            bindingNavigator1.MoveLastItem.Enabled = true;
        }

        private void ShowComicDetails(object sender, EventArgs e)
        {
            var ucComic = (ucComic)sender;
            var frmComicDetails = new FrmComicDetails(ucComic.ComicName, ucComic.ComicAuthor, ucComic.ComicUrl, ucComic.ComicCover, ComicSourceDic[ucComic.ComicSource]);
            frmComicDetails.ShowDialog();
        }
    }
}
